<?php

namespace App\Admin\Controllers;

use App\Models\AdminUsersModel;
use App\Models\AdminUsersRelatedModel;
use App\Models\ContractedCustomerModel;
use App\Models\CustomerFollowRecordModel;
use App\Models\FinanceExpensesModel;
use App\Models\FinanceIncomeModel;
use App\Models\StuffWagesModel;
use App\Models\TaskTransferRecordModel;
use App\Models\TaskUserModel;
use App\Models\TaskUserRelatedModel;
use App\Models\TaskUserRelatedRecordModel;
use App\Utils\NumberToChinese;
use Illuminate\Http\Request;
use App\Models\BlacklistModel;
use App\Models\CustomerModel;
use App\Models\TaskModel;
use App\Models\TaskRelatedModel;
use Carbon\Carbon;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Exception;

class AjaxController extends AdminController
{
    public function customerCreate(): JsonResponse
    {
        $customerName = trim(request()->post('customer_name'));
//        if (empty($customerName)) {
//            return failMessage('客户名不能为空');
//        }
        $age = trim(request()->post('age'));
        if (empty($age)) {
            return failMessage('年龄不能为空');
        } else {
            if ($age < 1) {
                return failMessage('年龄最小只能为1');
            }
        }
        $mobile = trim(request()->post('customer_mobile'));
        $pattern = '/^1[3-9]\d{9}$/';
        if ((string)$mobile === '' && (string)request()->post('customer_wechat') === '') return failMessage('手机号和微信号必须要填写一个');
        else {
            if ($mobile !== '') {
                if (!preg_match($pattern, $mobile)) {
                    return failMessage('手机号格式错误');
                }
            }
        }

        $operator = AdminUsersModel::query()->where('id', USERID)->first();
        CustomerModel::query()->insert([
            'serial_number' => serialNumber(),
            'customer_name' => is_null($customerName) || $customerName === '' ? '暂无' : $customerName,
            'age' => $age,
            'customer_gender' => request()->post('customer_gender'),
            'customer_mobile' => request()->post('customer_mobile'),
            'customer_wechat' => request()->post('customer_wechat'),
            'customer_qq' => request()->post('customer_qq'),
            'education' => request()->post('education'),
            'information_resources' => request()->post('information_resources'),
            'operator_id' => USERID,
            'customer_address' => request()->post('customer_address'),
            'extends' => json_encode([[
                'status' => __('task.followStatusArr')[2],
                'remark' => request()->post('remark'),
                'time' => Carbon::now()->format('Y-m-d H:i:s'),
            ]]),
            'forward_extends' => json_encode(['->' . $operator->name]),
//                'remark'                => request()->post('remark'),
            'main_id' => MAINID,
        ]);
        return success();
    }

    public function customerEdit(): JsonResponse
    {
        $categoryName = trim(request()->post('customer_name'));
        if (empty($categoryName)) {
            return failMessage('客户名不能为空');
        }
        $age = trim(request()->post('age'));
        if (empty($age)) {
            return failMessage('年龄不能为空');
        } else {
            if ($age < 1) {
                return failMessage('年龄最小只能为1');
            }
        }
        $mobile = trim(request()->post('customer_mobile'));
        $pattern = '/^1[3-9]\d{9}$/';
        if (!preg_match($pattern, $mobile)) {
            return failMessage('手机号格式错误');
        }
        $customer = CustomerModel::query()->where('id', request()->post('id'))->first();
        if (is_null($customer)) return fail(433);
        CustomerModel::query()
            ->where('id', request()->post('id'))
            ->update([
                'customer_name' => $categoryName,
                'age' => $age,
                'customer_gender' => request()->post('customer_gender'),
                'customer_mobile' => request()->post('customer_mobile'),
                'customer_wechat' => request()->post('customer_wechat'),
                'customer_qq' => request()->post('customer_qq'),
                'education' => request()->post('education'),
                'information_resources' => request()->post('information_resources'),
//                    'customer_status'       => request()->post('customer_status'),
                'customer_address' => request()->post('customer_address'),
                'extends' => json_encode(array_merge(json_decode($customer->extends, true), [[
                    'status' => __('task.followStatusArr')[2],
                    'remark' => request()->post('remark'),
                    'time' => Carbon::now()->format('Y-m-d H:i:s'),
                ]])),
//                    'remark'                => request()->post('remark'),
//                'operator_id' => auth()->user()->id,
            ]);
        return success();
    }

    public function customerDelete()
    {
        $customer = CustomerModel::query()
            ->where('id', request()->post('id'))->first();
        if (is_null($customer)) {
            return fail(433);
        }
        $customer->delete();
        return success();
    }


    public function customerShare(Request $request)
    {
        $user = AdminUsersModel::query()->where('id', $request->share)->first();
        if (is_null($user)) return failMessage('接收人不存在');
        $customer = CustomerModel::query()->where('id', request()->post('id'))->first();
        if (is_null($customer)) return fail(433);
        $checkCustomer = CustomerModel::query()
            ->where([
                'customer_mobile' => $customer->customer_mobile,
                'customer_wechat' => $customer->customer_wechat,
                'operator_id' => $request->share,
            ])->first();
        if (!is_null($checkCustomer)) return failMessage('该账号已拥有此客户资源');

        $arr = [
            'serial_number' => serialNumber(),
            'customer_name' => $customer->customer_name,
            'age' => $customer->age,
            'customer_gender' => $customer->customer_gender,
            'customer_mobile' => $customer->customer_mobile,
            'customer_wechat' => $customer->customer_wechat,
            'customer_qq' => $customer->customer_qq,
            'education' => $customer->education,
            'information_resources' => $customer->information_resources,
            'customer_address' => $customer->customer_address,
            'operator_id' => $request->share,
            'extends' => json_encode([[
                'status' => __('task.followStatusArr')[2],
                'remark' => request()->post('remark'),
                'time' => Carbon::now()->format('Y-m-d H:i:s'),
            ]]),
            'main_id' => MAINID,
            // 'forward_extends' => is_null($nextFollow)?[]:json_encode([$nextFollow])
        ];

        $nextFollow = null;
        if (!is_null($customer->forward_extends) || !empty($customer->forward_extends)) {
            $oldForwardExtends = json_decode($customer->forward_extends, true)[0];
            $forwardExtendsArr = explode('->', $oldForwardExtends);

            $lastFollow = $forwardExtendsArr[1] . '->' . $user->name;
            $nextFollow = $forwardExtendsArr[1] . '->' . $user->name;
            $customer->forward_extends = json_encode([$lastFollow]);

            $arr['forward_extends'] = json_encode([$nextFollow]);
        }
        $customer->is_forward = 1;
        $customer->save();
        CustomerModel::query()
            ->insert($arr);
        return success();
    }

    public function customerScore(): JsonResponse
    {
        $customer = CustomerModel::query()
            ->where('id', request()->post('id'))->first();
        if (is_null($customer)) {
            return fail(433);
        }
        $customer->score = request()->post('score');
        $customer->save();
        return success();
    }

    public function taskCreate(): JsonResponse
    {
        $taskName = trim(request()->post('task_name'));
        if (empty($taskName)) {
            return failMessage('客户名不能为空');
        }
        TaskModel::query()->insert([
            'serial_number' => serialNumber(),
            'task_name' => $taskName,
            'remark' => trim(request()->post('remark')),
            'main_id' => ISMAIN ? USERID : MAINID,
            'creator_id' => auth()->user()->id,
            'created_at' => Carbon::now(),
        ]);
        return success();
    }

    public function blacklistCreate(): JsonResponse
    {
        $name = trim(request()->post('name'));
        if (empty($name)) {
            return failMessage('客户名不能为空');
        }
        $age = trim(request()->post('age'));
        if (empty($age)) {
            return failMessage('年龄不能为空');
        } else {
            if ($age < 1) {
                return failMessage('年龄最小只能为1');
            }
        }
        $mobile = trim(request()->post('mobile'));
        $pattern = '/^1[3-9]\d{9}$/';
        if (!preg_match($pattern, $mobile)) {
            return failMessage('手机号格式错误');
        }
        BlacklistModel::query()->insert([
            'name' => request()->post('name'),
            'age' => request()->post('age'),
            'gender' => request()->post('gender'),
            'mobile' => request()->post('mobile'),
            'area' => request()->post('area'),
            'wechat' => request()->post('wechat'),
            'remark' => request()->post('remark'),
            'status' => 4,
            'operator_id' => auth()->user()->id,
            'main_id' => MAINID,
        ]);
        return success();
    }

    public function taskAllocation(): JsonResponse
    {
        $task = TaskModel::query()->where('id', request()->post('id'))->first();
        if (is_null($task)) return fail(433);
        $taskUser = TaskUserModel::query()
            ->where([
                'from_id' => request()->post('id'),
                'follow_user_id' => request()->post('follow_user_id'),
            ])->first();
        if (!is_null($taskUser)) return failMessage('该用户已拥有该资源');

        $taskUserId = TaskUserModel::query()->insertGetId([
            'from_id' => request()->post('id'),
            'task_id' => request()->post('id'),
            'follow_user_id' => request()->post('follow_user_id'),
            'total_task_num' => $task->total_task_num,
            'operator_id' => USERID,
            'main_id' => MAINID,
        ]);

        $taskRelated = TaskRelatedModel::query()
            ->where('task_id', request()->post('id'))->get()->toArray();

        $arr = [];
        foreach ($taskRelated as $value) {
            $arr[] = [
                'task_user_id' => $taskUserId,
                'task_related_id' => $value['id'],
            ];
        }
        TaskUserRelatedModel::query()->insert($arr);
        return success();
    }

    public function taskTransfer(Request $request)
    {
        $task = TaskModel::query()->where('id', request()->post('id'))->first();
        if (is_null($task)) return fail(433);

        $check = TaskModel::query()
            ->where('from_id', request()->post('id'))
            ->where('creator_id', $request->follow_user_id)
            ->first();
        if (!is_null($check)) return failMessage('目标公司已拥有该资源');

        $user = AdminUsersRelatedModel::query()
            ->where('user_id', $request->follow_user_id)
            ->first();

        $taskId = TaskModel::query()->insertGetId([
            'serial_number' => serialNumber(),
            'task_name' => $task->task_name,
            'remark' => $task->remark,
            'total_task_num' => $task->total_task_num,
            'creator_id' => $request->follow_user_id,
            'main_id' => $user->main_id == 0 ? $user->user_id : $user->main_id,
            'from_id' => request()->post('id')
        ]);
        $taskRelated = TaskRelatedModel::query()->where('task_id', $request->id)->get()->toArray();

        $user = AdminUsersModel::query()
            ->where('id', $request->follow_user_id)->first();

        TaskTransferRecordModel::query()->insert([
            'task_id' => request()->post('id'),
            'company_name' => $user->name,
            'operator_id' => USERID,
            'main_id' => MAINID
        ]);

        $arr = [];
        foreach ($taskRelated as $value) {
            $arr[] = [
                'task_id' => $taskId,
                'name' => $value['name'],
                'age' => $value['age'],
                'gender' => $value['gender'],
                'mobile' => $value['mobile'],
                'area' => $value['area'],
                'wechat' => $value['wechat'],
                'remark' => $value['remark'],
                'operator_id' => $request->follow_user_id,
            ];
        }
        TaskRelatedModel::query()->insert($arr);
        return success();
    }

    public function taskForward(): JsonResponse
    {
        $task = TaskModel::query()->where('id', request()->post('id'))
            ->first();
        if ((int)request()->post('follow_user_id') === $task->follow_user_id) return failMessage('不可转赠给同一个人');
        $arr[] = [
            'intentional_num' => $task->intentional_num,
            'invalid_num' => $task->invalid_num,
            'none_reply_num' => $task->none_reply_num,
            'hang_up_num' => $task->hang_up_num,
            'blacklist_num' => $task->blacklist_num,
            'completion_progress_num' => $task->completion_progress_num,
            'total_task_num' => $task->total_task_num,
            'from_follow_user' => DB::query()->from('admin_users')
                ->where('id', $task->follow_user_id)->value('name'),
            'to_follow_user' => DB::query()->from('admin_users')
                ->where('id', request()->post('follow_user_id'))
                ->value('name'),
            'operator' => auth()->user()->name,
            'operated_at' => Carbon::now()
                ->format('Y-m-d H:i:s'),
        ];
        if (!is_null($task->extends)) {
            $arr = array_merge(json_decode($task->extends, true), $arr);
        }
        $task->extends = $arr;
        $task->save();

        $id = TaskModel::query()->insertGetId([
            'serial_number' => serialNumber(),
            'task_name' => $task->task_name,
            'follow_user_id' => request()->post('follow_user_id'),
            'remark' => $task->remark,
            'creator_id' => $task->creator_id,
            'total_task_num' => $task->total_task_num,
        ]);

        $related = TaskRelatedModel::query()->where('task_id', $task->id)
            ->get()->toArray();
        $relatedArr = [];
        foreach ($related as $value) {
            $relatedArr[] = [
                'task_id' => $id,
                'name' => $value['name'],
                'gender' => $value['gender'],
                'age' => $value['age'],
                'area' => $value['area'],
                'mobile' => $value['mobile'],
                'wechat' => $value['wechat'],
                'remark' => $value['remark'],
                'follow_user_id' => request()->post('follow_user_id'),
                'operator_id' => auth()->user()->id,
            ];
        }
        TaskRelatedModel::query()->insert($relatedArr);
        return success();
    }

    public function taskImport(Request $request)
    {
        $files = $request->file('file');
        $ext = $files->extension();
        if (!in_array($ext, ['xlsx', 'xls', 'csv'])) return failMessage('文件格式错误');

        $path = $files->store(date('Y') . '/' . date('m') . '/' . date('d'));
        $filePath = public_path() . '/upload/' . $path;

        DB::beginTransaction();
        try {
            $reader = IOFactory::createReader(ucfirst($ext));

            $objSpreadsheet = $reader->load($filePath);

            $objWorksheet = $objSpreadsheet->getSheet(0);//读取第一个工作表
            $highestRow = $objWorksheet->getHighestRow();       // 取得总行数

            $data = $objWorksheet->toArray();
            unset($data[0]);

            $task = TaskModel::query()->where('id', $request->id)->first();

            $arr = [];
            foreach ($data as $key => $value) {
                $value = array_slice($value, 0, 7);
                if (is_null($value[0])) {
                    return failMessage('姓名不能为空');
                };
                $pattern = '/^1[3-9]\d{9}$/';
                if (!is_null($value[4]) && !preg_match($pattern, $value[4])) {
                    return failMessage('手机号:' . $value[4] . '格式错误');
                }

                $arr[] = [
                    'task_id' => $request->id,
                    'name' => $value[0],
                    'gender' => is_null($value[1]) ? 2 : $value[1] == '男' ?? 0,
                    'age' => is_null($value[2]) || $value[2] == '' ? 0 : $value[2],
                    'area' => $value[3],
                    'mobile' => $value[4],
                    'wechat' => $value[5],
                    'remark' => $value[6],
                    'operator_id' => auth()->user()->id,
                ];
            }

            $task->total_task_num = count($data);
            $task->save();
            TaskRelatedModel::query()->insert($arr);
            DB::commit();
            unlink($filePath);
            return success();
        } catch (Exception $e) {
            DB::rollBack();
            Log::debug('task-import:' . $e->getMessage());
            return failMessage($e->getMessage());
        }
    }

    public function taskDelete(): JsonResponse
    {
        $model = TaskModel::query()->where('id', request()->post('id'))->first();
        if (is_null($model)) return fail(433);
        $model->delete();

        $related = TaskRelatedModel::query()->where('task_id', $model->id)->first();
        if (!is_null($related)) TaskRelatedModel::query()->where('task_id', $model->id)->delete();

        return success();
    }

    public function taskFollowUp(Request $request): JsonResponse
    {
        $taskUserRelated = TaskUserRelatedModel::query()
            ->where('id', $request->id)
            ->first();
        if (is_null($taskUserRelated)) return fail(433);

        $arr[] = [
            'status' => __('task.followStatusArr')[$request->status],
            'remark' => $request->remark,
            'time' => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        if (!is_null($taskUserRelated->extends)) $arr = array_merge(json_decode($taskUserRelated->extends, true), $arr);

        $taskUserRelated->extends = $arr;
        $taskUserRelated->status = $request->status;
        $taskUserRelated->follow_up_at = Carbon::now()->toDateTimeString();
        $taskUserRelated->save();

        $taskUser = TaskUserModel::query()
            ->where('id', $taskUserRelated->task_user_id)->first();
        switch ((int)$request->status) {
            case 0:
                $taskUser->none_reply_num += 1;//无人接听
                break;
            case 1:
                $taskUser->hang_up_num += 1;//接通挂断
                break;
            case 2:
                $taskUser->intentional_num += 1;//有意向
                break;
            case 3:
                $taskUser->invalid_num += 1;//无效
                break;
            default:
                $taskUser->blacklist_num += 1;//黑名单
        }
        $taskUser->completion_progress_num += 1;//完成进度
        $taskUser->save();

        $taskRelated = TaskRelatedModel::query()
            ->where('id', $taskUserRelated->task_related_id)->first();

        $customer = CustomerModel::query()
            ->where('operator_id', $taskUser->follow_user_id)
            ->where(function ($query) use ($taskRelated) {
                $query->where('customer_mobile', $taskRelated->mobile)
                    ->where('customer_wechat', $taskRelated->wechat);
            })
            ->first();

        if ((int)$request->status === 2 && is_null($customer)) {
            $operator = AdminUsersModel::query()->where('id', USERID)->first();
            CustomerModel::query()->insert([
                'serial_number' => serialNumber(),
                'customer_name' => $taskRelated->name,
                'age' => $taskRelated->age,
                'customer_gender' => $taskRelated->gender,
                'customer_mobile' => $taskRelated->mobile,
                'customer_wechat' => $taskRelated->wechat,
                'main_id' => MAINID,
                'operator_id' => $taskUser->follow_user_id,
                'remark' => is_null($taskRelated->remark) ? null
                    : $taskRelated->remark,
                'extends' => json_encode($arr),
                'forward_extends' => json_encode(['->' . $operator->name]),
            ]);
        }

        if ((int)$request->status === 4) {
            BlacklistModel::query()->insert([
                'name' => $taskRelated->name,
                'age' => $taskRelated->age,
                'gender' => $taskRelated->gender,
                'area' => $taskRelated->area,
                'mobile' => $taskRelated->mobile,
                'wechat' => $taskRelated->wechat,
                'status' => 4,
                'extends' => json_encode($arr),
                'remark' => is_null($taskRelated->remark) ? null
                    : $taskRelated->remark,
                'follow_user_id' => $taskRelated->follow_user_id,
                'main_id' => MAINID,
                'operator_id' => $taskUser->follow_user_id,
            ]);
        }

        $record = TaskUserRelatedRecordModel::query()->where([
            'task_related_id' => $taskUserRelated->task_related_id,
            'operator_id' => $taskUser->follow_user_id,
            'date' => date('Y-m-d'),
        ])->first();

        if (is_null($record)) {
            TaskUserRelatedRecordModel::query()->insert([
                'task_related_id' => $taskUserRelated->task_related_id,
                'date' => date('Y-m-d'),
                'times' => 1,
                'operator_id' => $taskUser->follow_user_id,
            ]);
        } else {
            $record->times += 1;
            $record->save();
        }

        return success();
    }

    public function contractedCustomerCreate(Request $request): JsonResponse
    {
        if (is_null(trim($request->contract_no))) {
            return failMessage('请输入合同编号');
        }
//        if (is_null(trim($request->male_name))) {
//            return failMessage('请输入男方姓名');
//        }
        $pattern = '/^1[3-9]\d{9}$/';
        if (!is_null($request->male_mobile)
            && !preg_match($pattern, $request->male_mobile)
        ) {
            return failMessage('男方手机号格式错误');
        }
//        if (is_null(trim($request->female_name))) {
//            return failMessage('请输入女方姓名');
//        }
        if (!is_null($request->female_mobile)
            && !preg_match($pattern, $request->female_mobile)
        ) {
            return failMessage('女方手机号格式错误');
        }
        if (!preg_match('/^\d+(\.\d{2})?$/', $request->contract_amount)) {
            return failMessage('合同金额有误，仅能为两位小数');
        }

        ContractedCustomerModel::query()->insert([
            'contract_no' => $request->contract_no,
            'male_name' => is_null($request->male_name) || $request->male_name === '' ? '暂无' : $request->male_name,
            'male_blood_type' => $request->male_blood_type,
            'male_mobile' => $request->male_mobile,
            'female_name' => is_null($request->female_name) || $request->female_name === '' ? '暂无' : $request->female_name,
            'female_blood_type' => $request->female_blood_type,
            'female_mobile' => $request->female_mobile,
            'contact_address' => $request->contact_address,
            'contract_amount' => $request->contract_amount,
            'freeze_date' => $request->freeze_date,
            'remark' => $request->remark,
            'operate_id' => request()->post('operator_id'),
            'main_id' => MAINID,
        ]);
        return success();
    }

    public function contractedCustomerEdit(Request $request): JsonResponse
    {
        $model = ContractedCustomerModel::query()->where('id', $request->id)
            ->first();
        if (is_null($model)) {
            return fail(433);
        }
        if (is_null(trim($request->contract_no))) {
            return failMessage('请输入合同编号');
        }
        if (is_null(trim($request->male_name))) {
            return failMessage('请输入男方姓名');
        }
        $pattern = '/^1[3-9]\d{9}$/';
        if (!is_null($request->male_mobile)
            && !preg_match($pattern, $request->male_mobile)
        ) {
            return failMessage('男方手机号格式错误');
        }
        if (is_null(trim($request->female_name))) {
            return failMessage('请输入女方姓名');
        }
        if (!is_null($request->female_mobile)
            && !preg_match($pattern, $request->female_mobile)
        ) {
            return failMessage('女方手机号格式错误');
        }
        if (!preg_match(__('com.priceReg'), $request->contract_amount)) {
            return failMessage('合同金额有误，仅能为两位小数');
        }

        ContractedCustomerModel::query()->where('id', $request->id)
            ->update([
                'contract_no' => $request->contract_no,
                'male_name' => $request->male_name,
                'male_blood_type' => $request->male_blood_type,
                'male_mobile' => $request->male_mobile,
                'female_name' => $request->female_name,
                'female_blood_type' => $request->female_blood_type,
                'female_mobile' => $request->female_mobile,
                'contact_address' => $request->contact_address,
                'contract_amount' => $request->contract_amount,
                'freeze_date' => $request->freeze_date,
                'remark' => $request->remark
            ]);
        return success();
    }

    public function contractedCustomerDelete(Request $request): JsonResponse
    {
        $model = ContractedCustomerModel::query()->where('id', $request->id)
            ->first();
        if (is_null($model)) {
            return fail(433);
        }
        $model->delete();
        return success();
    }

    public function incomeCreate(Request $request): JsonResponse
    {
        if (is_null($request->contracted_customer_id)) {
            return failMessage('请选择客户');
        }
        if (!preg_match(__('com.priceReg'), $request->income_amount)) {
            return failMessage('打款金额有误，仅能为两位小数');
        }
        if (!preg_match(__('com.priceReg'),
            $request->actual_income_amount)
        ) {
            return failMessage('到账金额有误，仅能为两位小数');
        }
        if (is_null($request->income_date)) {
            return failMessage('请选择收款日期');
        }

        $model = FinanceIncomeModel::query()
            ->where('contracted_customer_id',
                $request->contracted_customer_id)
            ->orderByDesc('id')
            ->first();

        $data = $request->all();
        unset($data['_token']);

        $contracted = ContractedCustomerModel::query()
            ->where('id', $request->contracted_customer_id)->first();
        FinanceIncomeModel::query()
            ->insert(array_merge($data, [
                'income_received' => is_null($model)
                    ? $data['actual_income_amount']
                    : bcadd($data['actual_income_amount'],
                        $model->income_received, 2),
                'operate_id' => auth()->user()->id,
                'follow_user_id' => $contracted->operate_id,
                'main_id' => MAINID
            ]));

        return success();
    }

    public function incomeDelete(Request $request): JsonResponse
    {
        $model = FinanceIncomeModel::query()->where('id', $request->id)
            ->first();
        if (is_null($model)) {
            return fail(433);
        }

        $model->delete();
        return success();
    }

    public function incomeAudit(Request $request): JsonResponse
    {
        $model = FinanceIncomeModel::query()->where('id', $request->id)
            ->first();
        if (is_null($model)) {
            return fail(433);
        }
        $model->status = $request->status;
        $model->audit_remark = $request->audit_remark;
        $model->audit_id = auth()->user()->id;
        $model->audit_at = Carbon::now()->toDateTimeString();
        $model->save();
        return success();
    }

    public function getContractUserAccountInfo(Request $request): JsonResponse
    {
        return success([
            'income' => FinanceIncomeModel::query()->where([
                'contracted_customer_id' => $request->id,
                'status' => 1,
            ])->sum('actual_income_amount'),
            'expense' => FinanceExpensesModel::query()->where([
                'contracted_customer_id' => $request->id,
                'status' => 1,
            ])->sum('amount')
        ]);
    }

    public function expenseCreate(Request $request): JsonResponse
    {
        if (is_null($request->name)) return failMessage('名称不能为空');
        if (is_null($request->contracted_customer_id)) return failMessage('请选择客户');
        if (!preg_match(__('com.priceReg'), $request->amount)) return failMessage('金额有误，仅能为两位小数');
        if (is_null($request->date)) return failMessage('请选择日期');

        if (!is_null($request->file('file'))) {
            $files = $request->file('file');
            $ext = $files->extension();
            if (!in_array($ext, ['jpg', 'jpeg', 'png'])) return failMessage('图片格式错误');
            $files = $request->file('file');
            $ext = $files->extension();
            $path = $files->store(date('Y') . '/' . date('m') . '/' . date('d'));
            $path = '/upload/' . $path;
        } else $path = '';

        FinanceExpensesModel::query()->insert([
            'name' => $request->name,
            'contracted_customer_id' => $request->contracted_customer_id,
            'num' => $request->num,
            'amount' => $request->amount,
            'date' => $request->date,
            'type' => $request->type,
            'invoice_type' => $request->invoice_type,
            'invoice_proof' => $path,
            'remark' => $request->remark,
            'operate_id' => auth()->user()->id,
            'main_id' => MAINID,
        ]);

        return success();
    }

    public function expenseEdit(Request $request): JsonResponse
    {
        if (is_null($request->name)) return failMessage('名称不能为空');
        if (is_null($request->contracted_customer_id)) return failMessage('请选择客户');
        if (!preg_match(__('com.priceReg'), $request->amount)) return failMessage('金额有误，仅能为两位小数');
        if (is_null($request->date)) return failMessage('请选择日期');

        $model = FinanceExpensesModel::query()->where('id', $request->id)->first();
        if (is_null($model)) return fail(433);

        if (!is_null($request->file('file'))) {
            $files = $request->file('file');
            $ext = $files->extension();
            if (!in_array($ext, ['jpg', 'jpeg', 'png'])) return failMessage('图片格式错误');
            $path = $files->store(date('Y') . '/' . date('m') . '/' . date('d'));
            $path = '/upload/' . $path;
            unlink(public_path() . $path);
        } else $path = !is_null($model->invoice_proof) ? $model->invoice_proof : '';

        $model->name = $request->name;
        $model->contracted_customer_id = $request->contracted_customer_id;
        $model->num = $request->num;
        $model->amount = $request->amount;
        $model->date = $request->date;
        $model->type = $request->type;
        $model->invoice_type = $request->invoice_type;
        $model->invoice_proof = $path;
        $model->remark = $request->remark;
        $model->save();
        return success();
    }

    public function expenseDelete(Request $request): JsonResponse
    {
        $model = FinanceExpensesModel::query()->where('id', $request->id)
            ->first();
        if (is_null($model)) return fail(433);

        $model->delete();
        return success();
    }

    public function expenseAudit(Request $request): JsonResponse
    {
        $model = FinanceExpensesModel::query()->where('id', $request->id)
            ->first();
        if (is_null($model)) {
            return fail(433);
        }
        $model->status = $request->status;
        $model->audit_remark = $request->audit_remark;
        $model->audit_id = auth()->user()->id;
        $model->audit_at = Carbon::now()->toDateTimeString();
        $model->save();
        return success();
    }

    public function wagesCreate(Request $request): JsonResponse
    {
        if (is_null($request->stuff)) return failMessage('请选择员工');
        if (is_null($request->date)) return failMessage('请选择日期');
        if (!preg_match(__('com.priceReg'), $request->basic_wages)) return failMessage('基本薪资有误，仅能为两位小数');
        if (!preg_match(__('com.priceReg'), $request->commission)) return failMessage('提成有误，仅能为两位小数');
        if (!preg_match(__('com.priceReg'), $request->deduct)) return failMessage('应扣费用金额有误，仅能为两位小数');
        if (!preg_match(__('com.priceReg'), $request->actual_wages)) return failMessage('实发工资金额有误，仅能为两位小数');

        StuffWagesModel::query()->insert([
            'date' => $request->date,
            'user_id' => $request->stuff,
            'basic_wages' => $request->basic_wages,
            'commission' => $request->commission,
            'deduct' => $request->deduct,
            'actual_wages' => $request->actual_wages,
            'remark' => $request->remark,
            'operate_id' => auth()->user()->id,
            'main_id' => MAINID,
        ]);
        return success();
    }

    public function wagesEdit(Request $request): JsonResponse
    {
        if (is_null($request->stuff)) return failMessage('请选择员工');
        if (is_null($request->date)) return failMessage('请选择日期');
        if (!preg_match(__('com.priceReg'), $request->basic_wages)) return failMessage('基本薪资有误，仅能为两位小数');
        if (!preg_match(__('com.priceReg'), $request->commission)) return failMessage('提成有误，仅能为两位小数');
        if (!preg_match(__('com.priceReg'), $request->deduct)) return failMessage('应扣费用金额有误，仅能为两位小数');
        if (!preg_match(__('com.priceReg'), $request->actual_wages)) return failMessage('实发工资金额有误，仅能为两位小数');

        $model = StuffWagesModel::query()->where('id', $request->id)->first();
        if (is_null($model)) return fail(433);
        else if ($model->status !== 0) return failMessage('已审核的信息无法再次修改');
        $model->user_id = $request->stuff;
        $model->date = $request->date;
        $model->basic_wages = $request->basic_wages;
        $model->commission = $request->commission;
        $model->deduct = $request->deduct;
        $model->actual_wages = $request->actual_wages;
        $model->remark = $request->remark;
        $model->save();
        return success();
    }

    public function wagesDelete(Request $request): JsonResponse
    {
        $model = StuffWagesModel::query()->where('id', $request->id)->first();
        if (is_null($model)) return fail(433);
        $model->delete();
        return success();
    }

    public function wagesAudit(Request $request): JsonResponse
    {
        $model = StuffWagesModel::query()->where('id', $request->id)->first();
        if (is_null($model)) return fail(433);
        $model->status = $request->status;
        $model->audit_remark = $request->audit_remark;
        $model->audit_id = auth()->user()->id;
        $model->audit_at = Carbon::now()->toDateTimeString();
        $model->save();
        return success();
    }

    public function stuffReportForms(Request $request)
    {
        if (is_null($request->id)) return failMessage('请选择员工');
        $userInfo = AdminUsersModel::query()
            ->leftJoin('admin_users_related', 'admin_users_related.user_id', 'admin_users.id')
            ->where('user_id', $request->id)->first();
        if (is_null($userInfo)) return fail(433);
        $data['name'] = $userInfo->name;
        $data['mobile'] = $userInfo->mobile;
        $data['age'] = is_null($userInfo->id_number) ? '' : getAge($userInfo->id_number);
        $data['id_number'] = $userInfo->id_number;
        $data['address'] = $userInfo->living_address;
        $data['service_date'] = $userInfo->service_date;
        $data['work_age'] = is_null($userInfo->service_date) ? '' : getServiceDate($userInfo->service_date);
        $data['sign_num'] = ContractedCustomerModel::query()
            ->where('operate_id', $request->id)->count();
        $data['total_income'] = FinanceIncomeModel::query()
            ->where([
                'operate_id' => $request->id,
                'status' => 1
            ])->sum('actual_income_amount');
        $data['customer_expenses'] = FinanceExpensesModel::query()
            ->where([
                'operate_id' => $request->id,
                'status' => 1
            ])->sum('amount');
        $data['wages'] = StuffWagesModel::query()
            ->where([
                'user_id' => $request->id,
                'status' => 1
            ])
            ->sum('actual_wages');
        $data['make_money'] = ContractedCustomerModel::query()
            ->where('operate_id', $request->id)
            ->sum('contract_amount');

        $results = DB::query()
            ->fromSub(function ($query) use ($request) {
                $incomeQuery = DB::table('finance_income')
                    ->select(
                        DB::raw('LEFT(income_date, 7) as month'),
                        DB::raw('SUM(`actual_income_amount`) as income'),
                        DB::raw('null as expense'),
                        DB::raw('null as contracted_count'),
                        DB::raw('null as wages'),
                        DB::raw('null as output'),
                    )
                    ->where('follow_user_id', $request->id)
                    ->where('status', 1)
                    ->where(DB::raw('LEFT(income_date, 4)'), $request->date)
                    ->groupBy(DB::raw('LEFT(income_date, 7)'));

                $expenseQuery = DB::table('finance_expenses')
                    ->select(
                        DB::raw('LEFT(`date`, 7) as month'),
                        DB::raw('null as income'),
                        DB::raw('SUM(`amount`) as expense'),
                        DB::raw('null as contracted_count'),
                        DB::raw('null as wages'),
                        DB::raw('null as output'),
                    )
                    ->where('follow_user_id', $request->id)
                    ->where('status', 1)
                    ->where(DB::raw('LEFT(date, 4)'), $request->date)
                    ->groupBy(DB::raw('LEFT(date, 7)'));

                $contractQuery = DB::table('contracted_customer')
                    ->select(
                        DB::raw('LEFT(`created_at`, 7) as month'),
                        DB::raw('null as income'),
                        DB::raw('null as expense'),
                        DB::raw('count(*) as contracted_count'),
                        DB::raw('null as wages'),
                        DB::raw('null as output'),
                    )
                    ->where('operate_id', $request->id)
                    ->where(DB::raw('LEFT(created_at, 4)'), $request->date)
                    ->groupBy(DB::raw('LEFT(created_at, 7)'));

                $wagesQuery = DB::table('stuff_wages')
                    ->select(
                        DB::raw('LEFT(`date`, 7) as month'),
                        DB::raw('null as income'),
                        DB::raw('null as expense'),
                        DB::raw('null as contracted_count'),
                        DB::raw('SUM(`actual_wages`) as wages'),
                        DB::raw('null as output'),
                    )
                    ->where('user_id', $request->id)
                    ->where('status', 1)
                    ->where(DB::raw('LEFT(date, 4)'), $request->date)
                    ->groupBy(DB::raw('LEFT(date, 7)'));

                $outputQuery = DB::table('contracted_customer')
                    ->select(
                        DB::raw('LEFT(`created_at`, 7) as month'),
                        DB::raw('null as income'),
                        DB::raw('null as expense'),
                        DB::raw('null as contracted_count'),
                        DB::raw('null as wages'),
                        DB::raw('SUM(`contract_amount`) as output'),
                    )
                    ->where('operate_id', $request->id)
                    ->where(DB::raw('LEFT(created_at, 4)'), $request->date)
                    ->groupBy(DB::raw('LEFT(created_at, 7)'));

                $query->from($incomeQuery)
                    ->unionAll($expenseQuery)
                    ->unionAll($contractQuery)
                    ->unionAll($wagesQuery)
                    ->unionAll($outputQuery);
            },
                'combined_data')
            ->select(
                'month',
                DB::raw('FORMAT(SUM(income), 2) as total_income'),    // 总收入
                DB::raw('FORMAT(SUM(expense), 2) as total_expense'),  // 总支出
                DB::raw('SUM(contracted_count) as total_contracted_count'),  // 总签单数
                DB::raw('FORMAT(SUM(wages), 2) as total_wages'),  // 总工资
                DB::raw('FORMAT(SUM(output), 2) as total_output'),  // 总工资
            )
            ->groupBy('month')->get()->toArray();
        $data['list'] = $results;
        return success($data);
    }

    public function stuffDelete(Request $request)
    {
        $adminUser = AdminUsersModel::query()->where('id', $request->id)->first();
        if (is_null($adminUser)) return fail(433);
        $adminUser->delete();
        AdminUsersRelatedModel::query()->where('user_id', $request->id)->delete();
        return success();
    }

    public function customerFollowUp(Request $request)
    {
        $model = CustomerModel::query()->where('id', $request->id)->first();
        if (is_null($model)) return fail(433);

        $arr[] = [
            'status' => __('task.followStatusArr')[2],
            'remark' => $request->remark,
            'time' => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        if (!is_null($model->extends)) {
            $arr = array_merge($model->extends,
                $arr);
        }

        $model->follow_up_at = Carbon::now()->toDateTimeString();
        $model->extends = $arr;
        $model->save();

        $record = CustomerFollowRecordModel::query()
            ->where('customer_id', $model->id)
            ->where('date', date('Y-m-d'))->first();
        if (is_null($record)) {
            CustomerFollowRecordModel::query()->insert([
                'customer_id' => $request->id,
                'date' => date('Y-m-d'),
                'times' => 1,
                'operator_id' => USERID
            ]);
        } else {
            $record->times += 1;
            $record->save();
        }
        return success();
    }

    public function stuffStatusTrans(Request $request)
    {
        $model = AdminUsersModel::query()
            ->where('id', $request->id)
            ->first();

        if (is_null($model)) return fail(433);

        $model->status = $model->status ? 0 : 1;
        $model->save();
        return success();
    }

    public function getScore(Request $request)
    {
        $customer = CustomerModel::query()
            ->where('id', $request->id)->first();
        if (is_null($customer)) return fail(433);
        return success(['score' => $customer->score]);
    }

    public function saveScore(Request $request)
    {
        $customer = CustomerModel::query()
            ->where('id', $request->id)->first();
        if (is_null($customer)) return fail(433);
        $customer->score = $request->score;
        $customer->save();
        return success();
    }

    public function numberToChinese(Request $request)
    {
        Log::debug($request->amount);
        return success(NumberToChinese::convert(str_replace(',', '', $request->amount)));
    }
}
